﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Implementation.Console
{
    public sealed class ServiceWorker
    {
        #region Attributes
        /// <summary>
        /// Flag to know if the component has been disposed
        /// </summary>
        private bool _disposed;
        /// <summary>
        /// Event used to notify a change in a property
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region Properties
        /// <summary>
        /// The background worker used to manage the thread
        /// </summary>
        private System.ComponentModel.BackgroundWorker BgWorker { get; set; }
        /// <summary>
        /// Object worker
        /// </summary>
        public IWorker Worker { get; private set; }
        /// <summary>
        /// Gets or sets loop timeout
        /// </summary>
        public TimeSpan LoopTimer { get; set; }
        /// <summary>
        /// Gets <c>true</c> if worker is busy, <c>false</c> if not
        /// </summary>
        public bool IsWorkerBusy
        {
            get
            {
                bool busy = false;
                if (BgWorker != null)
                    busy = BgWorker.IsBusy;
                return busy;
            }
        }
        #endregion

        #region Constructor / Destructor
        /// <summary>
        /// Initialize the worker
        /// </summary>
        public ServiceWorker(IWorker worker, TimeSpan loopTimer)
        {
            Worker = worker;
            LoopTimer = loopTimer;
            BgWorker = new System.ComponentModel.BackgroundWorker();
            BgWorker.WorkerSupportsCancellation = true;
            BgWorker.WorkerReportsProgress = false;
            BgWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(Background_WorkCompleted);
            BgWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(Background_Working);
        }
        /// <summary>
        /// Destructor
        /// </summary>
        ~ServiceWorker()
        {
            Dispose(false);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Cancel the background work
        /// </summary>
        public void Cancel()
        {
            if (this.BgWorker.IsBusy & !this.BgWorker.CancellationPending)
            {

                BgWorker.CancelAsync();
                int cpt = 0;
                while (this.BgWorker.IsBusy)
                {
                    System.Threading.Thread.Sleep(10);
                    if (cpt == 100)
                        break;
                    cpt++;
                }
            }
        }
        /// <summary>
        /// Start the background work
        /// </summary>
        public void Start()
        {
            if (!BgWorker.IsBusy)
            {
                BgWorker.RunWorkerAsync();
            }
        }
        /// <summary>
        /// Dispose the worker
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            if (Worker is IDisposable)
                ((IDisposable)Worker).Dispose();
            //GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Dispose the worker
        /// </summary>
        /// <param name="disposing">[in] <c>true</c> for disposing resources, <c>false</c> otherwise</param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!_disposed)
            {
                // If disposing, dispose all ressources
                if (disposing)
                {
                    this.Cancel();
                    this.BgWorker.Dispose();
                    if (Worker is IDisposable)
                        ((IDisposable)Worker).Dispose();
                }
                // Note disposing has been done.
                _disposed = true;
            }
        }
        /// <summary>
        /// Raise the propertychanged event 
        /// </summary>
        /// <param name="propertyName">Mame of the property</param>
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        #region Event Handler
        /// <summary>
        /// Execute task
        /// </summary>
        /// <param name="sender">[in] <c>BgWorker</c></param>
        /// <param name="e">[in] Arguments</param>
        private void Background_Working(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (!BgWorker.CancellationPending)
            {
                try
                {
                    Worker.ExecuteTask();
                    System.Threading.Thread.Sleep(LoopTimer);
                }
                catch (System.Exception ex)
                {
                    ExceptionHandler.CatchException(ex);
                }
            }

            // Set the flag if the process has been canceled
            if (BgWorker.CancellationPending)
            {
                e.Cancel = true;
            }
        }
        /// <summary>
        /// Manage the end of the process
        /// </summary>
        /// <param name="sender">[in] <c>BgWorker</c></param>
        /// <param name="e">[in] Completed arguments</param>
        private void Background_WorkCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                Logger.InfoFormat("The worker '{0}' has been cancelled", Worker == null ? "?" : Worker.Name);
            }
            else
            {
                if (e.Error != null)
                {
                    ExceptionHandler.CatchException(e.Error);
                }
                else
                {
                    Logger.InfoFormat("The worker '{0}' has completed it's work", Worker == null ? "?" : Worker.Name);
                }
            }
        }
        #endregion

    }

}
